<!-- <template>
  <button @click="handleCreateFile">创建并写入文件</button>
</template>

<script setup>
import { ref } from 'vue';

const fileEntry = ref(null);

// 处理创建文件和写入文件的函数
const handleCreateFile = async () => {
  try {
    // 请求文件系统
    const fs = await new Promise((resolve, reject) => {
      window.webkitRequestFileSystem(
        window.TEMPORARY, // 临时存储
        1024 * 1024 * 5, // 5MB大小
        fs => resolve(fs),
        e => reject(e)
      );
    });

    // 创建文件
    fileEntry.value = await new Promise((resolve, reject) => {
      fs.root.getFile(
        'newFile.txt', // 文件名
        { create: true }, // 如果文件不存在则创建
        fileEntry => resolve(fileEntry),
        e => reject(e)
      );
    });
    console.log('FileSlot successfully create');

    // 写入文件
    await new Promise((resolve, reject) => {
      fileEntry.value.createWriter(
        fileWriter => {
          fileWriter.onwrite = () => {
            console.log('File successfully written');
            resolve();
          };
          fileWriter.onerror = e => {
            console.log('Write failed', e);
            reject(e);
          };
          const blob = new Blob(['Hello, world!'], { type: 'text/plain' });
          fileWriter.write(blob);
        },
        e => {
          reject(e);
        }
      );
    });
  } catch (e) {
    console.error('Error handling file system operations:', e);
  }
};
</script> -->



<!-- 
<template>
  <div></div>
</template>

<script>
export default {
  data() {
    return {
      fileEntry: null,
      // 其他数据...
    };
  },
  methods: {
    requestFileSystem() {
      // 请求文件系统
      window.webkitRequestFileSystem(
        window.TEMPORARY, // 临时存储
        1024 * 1024 * 5, // 5MB大小
        fs => {
          this.fileSystem = fs;
          this.createFile();
        },
        e => {
          console.log('Error', e);
        }
      );
    },
    createFile() {
      // 创建一个文件
      this.fileSystem.root.getFile(
        'newFile.txt', // 文件名
        { create: true }, // 如果文件不存在则创建
        fileEntry => {
          this.fileEntry = fileEntry;
          console.log('FileSlot successfully create');
          this.writeFile();
        },
        e => {
          console.log('Error', e);
        }
      );
    },
    writeFile() {
      // 写入文件
      this.fileEntry.createWriter(
        fileWriter => {
          fileWriter.onwrite = () => {
            console.log('File successfully written');
          };
          fileWriter.onerror = e => {
            console.log('Write failed', e);
          };
          const blob = new Blob(['Hello, world!'], { type: 'text/plain' });
          fileWriter.write(blob);
        },
        e => {
          console.log('Error', e);
        }
      );
    }
  },
  mounted() {
    this.requestFileSystem();
  }
};
</script> -->



<!-- <template>
  <div></div>
</template>

<script setup>
import { ref } from 'vue';

// 创建一个响应式变量来存储数据
const dataStore = ref(null);

// 定义一个异步函数来初始化IndexedDB
async function initDB() {
  const request = indexedDB.open('myDatabase', 1);

  request.onupgradeneeded = (event) => {
    const db = event.target.result;
    if (!db.objectStoreNames.contains('myStore')) {
      db.createObjectStore('myStore', { keyPath: 'id' });
    }
  };

  request.onsuccess = (event) => {
    const db = event.target.result;
    dataStore.value = {
      addData: (data) => {
        const transaction = db.transaction('myStore', 'readwrite');
        const store = transaction.objectStore('myStore');
        const request = store.add(data);
        request.onsuccess = () => console.log('数据添加成功');
        request.onerror = () => console.log('数据添加失败');
      },
      fetchData: () => {
        const transaction = db.transaction('myStore', 'readonly');
        const store = transaction.objectStore('myStore');
        const request = store.getAll();
        request.onsuccess = () => console.log(request.result);
        request.onerror = () => console.log('数据获取失败');
      }
    };
  };

  request.onerror = (event) => {
    console.log('数据库打开失败');
  };
}

// 在组件挂载时初始化IndexedDB
initDB();
</script> -->



<!-- <template>
  <div>
    <button @click="writeDataToDB">写入数据到数据库</button>
    <button @click="readAllDataFromDB">读取所有数据</button>
    <button @click="deleteSpecificData">删除特定数据</button>
    <button @click="updateSpecificData">修改特定数据</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';

// 响应式变量，用于存储数据库打开请求的结果
const db = ref(null);

// 写入数据到IndexedDB的函数
const writeDataToDB = async () => {
  if (!db.value) {
    console.log('数据库未初始化或打开失败');
    return;
  }

  try {
    // 打开一个事务，指定要读写的存储空间
    const transaction = db.value.transaction(['myStore'], 'readwrite');
    // 获取存储空间
    const store = transaction.objectStore('myStore');
    // 添加数据到存储空间
    const request = store.add({ id: Date.now(), data: 'Hello, world!' });

    request.onsuccess = function () {
      console.log('数据写入成功');
    };

    request.onerror = function (event) {
      console.error('数据写入失败', event.target.error);
    };
  } catch (error) {
    console.error('写入数据时发生错误', error);
  }
};

// 从IndexedDB读取所有数据的函数
const readAllDataFromDB = async () => {
  if (!db.value) {
    console.log('数据库未初始化或打开失败');
    return;
  }

  try {
    // 打开一个事务，指定要读取的存储空间
    const transaction = db.value.transaction(['myStore'], 'readonly');
    // 获取存储空间
    const store = transaction.objectStore('myStore');
    // 获取所有数据
    const request = store.getAll();

    request.onsuccess = function (event) {
      console.log('数据库中的数据:', event.target.result);
    };

    request.onerror = function (event) {
      console.error('数据读取失败', event.target.error);
    };
  } catch (error) {
    console.error('读取数据时发生错误', error);
  }
};

// 删除特定数据的函数
const deleteSpecificData = async () => {
  if (!db.value) {
    console.log('数据库未初始化或打开失败');
    return;
  }

  try {
    // 打开一个事务，指定要读写的存储空间
    const transaction = db.value.transaction(['myStore'], 'readwrite');
    // 获取存储空间
    const store = transaction.objectStore('myStore');
    // 假设要删除的数据ID为'id'
    const idToDelete = 1;
    // 删除特定ID的数据
    const request = store.delete(idToDelete);

    request.onsuccess = function () {
      console.log('数据删除成功');
    };

    request.onerror = function (event) {
      console.error('数据删除失败', event.target.error);
    };
  } catch (error) {
    console.error('删除数据时发生错误', error);
  }
};

// 修改特定数据的函数
const updateSpecificData = async () => {
  if (!db.value) {
    console.log('数据库未初始化或打开失败');
    return;
  }

  try {
    // 打开一个事务，指定要读写的存储空间
    const transaction = db.value.transaction(['myStore'], 'readwrite');
    // 获取存储空间
    const store = transaction.objectStore('myStore');
    // 假设要修改的数据ID为'some-id'
    const idToUpdate = 1;
    // 获取要修改的数据
    const getRequest = store.get(idToUpdate);

    getRequest.onsuccess = function(event) {
      const data = event.target.result;
      if (data) {
        // 修改数据
        data.data = 'Updated data';
        const putRequest = store.put(data);

        putRequest.onsuccess = function() {
          console.log('数据更新成功');
        };

        putRequest.onerror = function(event) {
          console.error('数据更新失败', event.target.error);
        };
      } else {
        console.log('未找到要更新的数据');
      }
    };

    getRequest.onerror = function(event) {
      console.error('获取数据失败', event.target.error);
    };
  } catch (error) {
    console.error('更新数据时发生错误', error);
  }
};

// 初始化IndexedDB的函数
const initDB = async () => {
  try {
    // 打开IndexedDB数据库，如果不存在则创建
    db.value = await new Promise((resolve, reject) => {
      const request = indexedDB.open('myDatabase', 1);

      request.onupgradeneeded = function (event) {
        const db = event.target.result;
        if (!db.objectStoreNames.contains('myStore')) {
          db.createObjectStore('myStore', { keyPath: 'id' });
        }
      };

      request.onsuccess = function (event) {
        resolve(event.target.result);
      };

      request.onerror = function (event) {
        reject('数据库打开失败');
      };
    });
  } catch (error) {
    console.error('数据库初始化失败', error);
  }
};

// 在组件挂载时初始化IndexedDB
initDB();
</script> -->



<template>
  <div>
    <el-row class="mb8">
      <el-button @click="initState" type="primary">创建数据库</el-button>
      <el-button @click="onOperation('deleteAll')" type="primary">清除数据库所有数据</el-button>
    </el-row>
    <el-button @click="onOperation('add')" type="primary">增</el-button>
    <el-button @click="onOperation('delete')" type="primary">删</el-button>
    <el-button @click="onOperation('update')" type="primary">改</el-button>
    <el-button @click="onOperation('query')" type="primary">查by主键</el-button>
    <el-button @click="onOperation('queryIndex')" type="primary">查by索引</el-button>
    <el-button @click="onOperation" type="primary">查-all</el-button>
    <el-row :gutter="24">
      <el-col :span="8">
        <div>书名：<el-input v-model="formData.title" /></div>
        <div>作者：<el-input v-model="formData.author" /></div>
        <div>需要修改/查询的数据主键(id)：<el-input v-model="mainKey" /></div>
        <div>需要查询的数据索引(title)：<el-input v-model="mainTitle" /></div>
      </el-col>
      <el-col :span="16">
        <div>查询结果：</div>
        <el-table :data="detailData" border>
          <el-table-column prop="id" label="主键"></el-table-column>
          <el-table-column prop="title" label="书名"></el-table-column>
          <el-table-column prop="author" label="作者"></el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        title: '书名',
        author: '作者'
      },
      mainKey: null,
      mainTitle: '',
      detailData: null
    }
  },
  // created() {
  //   this.initState()
  // },
  methods: {
    initState() {
      // 打开（或创建）一个名为 "myDatabase" 的数据库
      const request = indexedDB.open('myDatabase', 1)

      // onupgradeneeded 是 IndexedDB API 中的一个事件，它在数据库的版本发生变化时被触发。这通常发生在你打开数据库时指定了一个比当前数据库版本更高的版本号
      request.onupgradeneeded = function (event) {
        const db = event.target.result

        // 创建一个名为 "books" 的对象存储
        const objectStore = db.createObjectStore('books', {
          keyPath: 'id', // 主键
          autoIncrement: true // 主键（keyPath）是否自动增长
        })

        // 创建索引createIndex(参数一：索引的名称（字符串）；参数二：索引基于的键路径（字符串或数组）；参数三：一个对象，包含索引的配置选项，如unique（是否唯一）)
        objectStore.createIndex('titleIndex', 'title', { unique: false })
      }

      request.onerror = event => {
        console.error('数据库打开失败:' + event.target.errorCode)
      }
    },
    onOperation(type) {
      const _this = this
      const request = indexedDB.open('myDatabase', 1)
      request.onsuccess = function (event) {
        const db = event.target.result
        // 创建一个只读事务，涉及到 "books" 对象存储
        const transaction = db.transaction(['books'], 'readwrite')
        // 用于获取事务中的一个对象存储
        const objectStore = transaction.objectStore('books')

        // 增
        if (type === 'add') {
          objectStore.add(_this.formData)
        }
        // 删
        if (type === 'delete') {
          if (!_this.mainKey) {
            _this.$message.warning('请先输入你要删除的主键id')
            return
          }
          objectStore.delete(Number(_this.mainKey))
        }
        // 删-all
        if (type === 'deleteAll') {
          objectStore.clear()
        }
        // 改
        if (type === 'update') {
          if (!_this.mainKey) {
            _this.$message.warning('请先输入你要更新的主键id')
            return
          }
          objectStore.put({
            id: Number(_this.mainKey),
            ..._this.formData
          })
        }
        let getRequest
        // 查-主键
        if (type === 'query') {
          if (!_this.mainKey) {
            _this.$message.warning('请先输入你要查询的主键id')
            return
          }
          getRequest = objectStore.get(Number(_this.mainKey))
          // 查-索引
        } else if (type === 'queryIndex') {
          if (!_this.mainTitle) {
            _this.$message.warning('请先输入你要查询的索引对应的值')
            return
          }
          // 获取 "title" 索引
          const index = objectStore.index('titleIndex')
          getRequest = index.getAll(_this.mainTitle)
        } else {
          // 查-all
          getRequest = objectStore.getAll()
        }
        getRequest.onsuccess = function (event) {
          _this.detailData = event.target.result
          console.log('查询结果：', event.target.result)
        }
      }
    }
  }
}
</script>



